package com.easyclearance.baseutil;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

/**
 * HTTP工具
 *
 * @author robinzhang
 */
public class HttpUtil {
    /**
     * 请求类型： GET
     */
    public final static String GET = "GET";
    /**
     * 请求类型： POST
     */
    public final static String POST = "POST";
    
    /**
     * 缓冲区大小(缓冲区越大下载的越快,但是要根据自己的服务器配置)  
     */
    private static int BUFFER_SIZE = 10240; 
    /**
     * 模拟Http Get请求
     *
     * @param urlStr   请求路径
     * @param paramMap 请求参数
     * @return
     * @throws Exception
     */
    public static String get(String urlStr, Map<String, String> paramMap) throws Exception {
//        urlStr = urlStr + "?" + getParamString(paramMap);
        HttpURLConnection conn = null;
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            //设置通用的请求属性
            setHttpUrlConnection(conn, GET);
            //建立实际的连接
            conn.connect();
            //获取响应的内容
            return readResponseContent(conn.getInputStream());
        } finally {
            if (null != conn) conn.disconnect();
        }
    }

    public static void getFile(String urlStr, Map<String, String> paramMap,String filePath) throws Exception {
        urlStr = urlStr + "?" + getParamString(paramMap);
        HttpURLConnection conn = null;
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            //设置通用的请求属性
            setHttpUrlConnection(conn, GET);
            //建立实际的连接
            conn.connect();
            //获取响应的内容
            readResponseContentFile(conn.getInputStream(),filePath);
        } finally {
            if (null != conn) conn.disconnect();
        }
    }
    
    /**
     * 模拟Http Post请求
     *
     * @param urlStr   请求路径
     * @param paramMap 请求参数
     * @return
     * @throws Exception
     */
    public static String post(String urlStr, Map<String, String> paramMap) throws Exception {
        HttpURLConnection conn = null;
        PrintWriter writer = null;
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //获取请求参数
            String param = getParamString(paramMap);
            //获取URL连接
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("cookie", "c800=dccore0; YKJ_IS_DIWORK=1; YKJ_DIWORK_DATA=%7B%22data%22%3A%7B%22is_diwork%22%3A1%2C%22cur_qzid%22%3A%2225285%22%7D%2C%22key%22%3A%222bf44eb818ef9255e84e532ad5a201a8%22%7D; _WorkbenchCross_=Ultraman; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh-CN; yht_default_country=86; yht_default_login_type=normal; _yht_code_uuid=ebbd0121-aa2b-4363-bde3-53148ba9c4af; c800=dccore0; ck_safe_chaoke_csrf_token=53f7722e298dc3ca5a7b5214eb6f1a0c; PHPSESSID=2nm55e0d42jl0g5he8hjfhk0c5; a10=MDAxMTcwMTc3MTEzNjkzNjU4NDA; XSRF-TOKEN=AX_Y54VR359YKZ1WY3KTSYGELX8S!141831; Hm_lvt_b97569d26a525941d8d163729d284198=1681195985; Hm_lpvt_b97569d26a525941d8d163729d284198=1681195985; Hm_lvt_e8002ef3d9e0d8274b5b74cc4a027d08=1681195985; Hm_lpvt_e8002ef3d9e0d8274b5b74cc4a027d08=1681195985; SECKEY_ABVK=0Q+1Cks/4FTz/i22tJfcqEe2UemyZ0XgYVoKAVvopIQ%3D; BMAP_SECKEY=2zsfn8HWiX9vSbyzXL1jg_6GRPtfLq6Pu3RVDOkrpq6NjaCtUdYdmWriCFWWx0_ZDY6Vmwti2e-q67Ceh7KBdP6kkc19zmcVEbunfrLqSXyWt_9nPbSfNxS5vQ9pbirw0jjD3VSVK3RBsb1wObYr4gTMoOkl-YvQa67e7mjXWMOWKd1DYt6HgPrJv-CSTogY; at=0a2aade0-01fc-47fc-8794-d8b982150b11; JSESSIONID=FD7FE7E207898F522553B69109602140; yht_username_diwork=ST-4078-tLNhSO1kNCHXuLufdMA6-test__99ea7655-00a2-4bda-b23c-19ade37ea574; yht_usertoken_diwork=9wHYeVnjt5zelvLuXevj%2BVvKbzoAGqUpvFi8DzyhCqxf%2BtgBZPY%2FRhW%2FkiZyVkZQxbcXNvq%2BndcdydjVuNuO2w%3D%3D; multilingualFlag=true; timezone=UTC+08:00; language=001; locale=zh_CN; orgId=; theme=; newArch=true; sysid=diwork; n_f_f=true; wb_at=LMjqmtujsEGgLHnjG5AQtEtecF3sjsdrs; yht_access_token=bttQTdHSDhoTVc3ZnZNVEQ4WjYrSjRTNVNhMkN2ZFZGVGwvWjR2VVh6cTRKVUgzdG9zN2VzbmxaTkpEQ1pKUlhUMl9fYmlwLXRlc3QueXl1YXAuY29t__1bd1883da6131a90e8a1d2fe67ac2d13_1681196584159dccore0iuap-apcom-workbench166b7e06YT; defaultOrg=1525652227072458756; tenantid=0000L6YQ8AVLFUZPXD0000; languages=emhfQ04sMSwxLDE7ZW5fVVMsMiwxLDA7emhfVFcsMywxLDA=; a00=sBaeD54TfzuuXxjnPovXkne3SY4UXd5nj3Ya3iQ-g-0wMDAwTDZZUThBVkxGVVpQWEQwMDAwYDI5MDk5MzA3MTU4NjE1ODRgMDAwMEw2WVE4QVZMRlVaUFhEMDAwMGA5OWVhNzY1NS0wMGEyLTRiZGEtYjIzYy0xOWFkZTM3ZWE1NzRgMWBgNzk2ZjZlNzk2Zjc1MzIzMDMyMzM3NDY1NzM3NDMyYGBgMTUyNTY0MTc1NTkzOTU2OTY2N2BmYWxzZWBgMTY4MTE5NjU4NDE2MWB5bXNzZXM6OWFkNDBiODRkNjAzNjJkYjc1N2E5NTA2YTlmMGQxZGVgZGl3b3JrYA; a10=MDczNTgwOTczMTEzNzI1ODQxNjE; jDiowrkTokenMock=bttQTdHSDhoTVc3ZnZNVEQ4WjYrSjRTNVNhMkN2ZFZGVGwvWjR2VVh6cTRKVUgzdG9zN2VzbmxaTkpEQ1pKUlhUMl9fYmlwLXRlc3QueXl1YXAuY29t__1bd1883da6131a90e8a1d2fe67ac2d13_1681196584159dccore0iuap-apcom-workbench166b7e06YT");
            conn.setRequestProperty("domain-key", "oms");
            //设置通用请求属性
            setHttpUrlConnection(conn, POST);
            //建立实际的连接
            conn.connect();
            //将请求参数写入请求字符流中
            writer = new PrintWriter(conn.getOutputStream());
            writer.print(param);
            writer.flush();
            //读取响应的内容
            return readResponseContent(conn.getInputStream());
        } finally {
            if (null != conn) conn.disconnect();
            if (null != writer) writer.close();
        }
    }

    /**
     * 读取响应字节流并将之转为字符串
     *
     * @param in 要读取的字节流
     * @return
     * @throws IOException
     */
    private static String readResponseContent(InputStream in) throws IOException {
        Reader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            reader = new InputStreamReader(in);
            char[] buffer = new char[1024];
            int head = 0;
            while ((head = reader.read(buffer)) > 0) {
                content.append(new String(buffer, 0, head));
            }
            return content.toString();
        } finally {
            if (null != in) in.close();
            if (null != reader) reader.close();
        }
    }
    
    private static void readResponseContentFile(InputStream in,String filePath) throws IOException {
//    	String filePath = "src/a.pdf";
        Reader reader = null;
        FileOutputStream fos = null;
        byte[] buf = new byte[BUFFER_SIZE];  
        try {
            BufferedInputStream bfInput = new BufferedInputStream(in);
            fos = new FileOutputStream(filePath);
            int size = 0;
            while ((size = bfInput.read(buf)) != -1) {
            	fos.write(buf, 0, size);
            }
        } finally {
            if (null != in) in.close();
            if (null != reader) reader.close();
            fos.close();
        }
    }

    /**
     * 设置Http连接属性
     *
     * @param conn http连接
     * @return
     * @throws ProtocolException
     * @throws Exception
     */
    private static void setHttpUrlConnection(HttpURLConnection conn, String requestMethod) throws ProtocolException {
        conn.setRequestMethod(requestMethod);
        conn.setRequestProperty("domain-key", "oms");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        conn.setRequestProperty("Accept", "*");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("yht_access_token", "bttdk4vK2QyUGFadEJvblNBNVhuMWVVRHVwamorSnpzYjVSQk8yS1pGaUhKNHRvUHJKYVNNZkc3T3E1Q1hRdTRDWV9fYmlwLXRlc3QueXl1YXAuY29t__1bd1883da6131a90e8a1d2fe67ac2d13_1681868132163dccore0iuap-apcom-workbench166b7e06YT");
        if (null != requestMethod && POST.equals(requestMethod)) {
            conn.setDoOutput(true);
            conn.setDoInput(true);
        }
    }


    /**
     * 将参数转为路径字符串
     *
     * @param paramMap
     * @return
     */
    private static String getParamString(Map<String, String> paramMap) {
        if (null == paramMap || paramMap.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (String key : paramMap.keySet()) {
            builder.append("&")
                    .append(key).append("=").append(paramMap.get(key));
        }
        return builder.deleteCharAt(0).toString();
    }

    public static JSONObject sendPost(String url, String Params) throws IOException {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        String response = "";
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setReadTimeout(10*60*1000);
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = new OutputStreamWriter(
                    conn.getOutputStream());
            out.write(Params);
            out.flush();
            //读取响应
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response += lines;
            }
            reader.close();
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return JSONObject.parseObject(response);
    }

    public static void sendFilePost(String url, String Params,String filePath) throws IOException {

        OutputStreamWriter out = null;
        FileOutputStream fos = null;  
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //
            byte[] buf = new byte[BUFFER_SIZE];  
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Cookie", "c800=dccore0; c800=dccore0; _WorkbenchCross_=Ultraman; PHPSESSID=anoch49o6q71qsopvmd9854ou0; YKJ_IS_DIWORK=1; YKJ_DIWORK_DATA=%7B%22data%22%3A%7B%22is_diwork%22%3A1%2C%22cur_qzid%22%3A%2225285%22%7D%2C%22key%22%3A%222bf44eb818ef9255e84e532ad5a201a8%22%7D; _WorkbenchCross_=Ultraman; multilingualFlag=true; timezone=UTC+08:00; language=001; locale=zh_CN; orgId=; theme=; newArch=true; sysid=diwork; n_f_f=true; Hm_lvt_b97569d26a525941d8d163729d284198=1695353883,1695609274; Hm_lvt_e8002ef3d9e0d8274b5b74cc4a027d08=1695353883,1695609274; JSESSIONID=EE5B8E732C04A4100A0E3CAC962A1E07; yht_username_diwork=ST-7346-5CbCeUmyotrrK1mjD3cV-testC2__99ea7655-00a2-4bda-b23c-19ade37ea574; yht_usertoken_diwork=gw%2BgDqtHu719MsnN3CPwXHLj1XpKfVDaQJSMIxnBYzUuazGlqzfwr7fqLsH3f22lHNq1bQp8NyqISeEKrfvD0Q%3D%3D; yht_access_token=bttS1o1T2x5eUJmTjhyYjZxbU9SREpxQW45clIxZzJwdXZ3eG01L2dwMndZYlZKb0xzeXBEdUtvRGVmbENDVWljaF9fYmlwLXRlc3QueW9ueW91Y2xvdWQuY29t__efe01ac3165cf69d3c729add33bd2680_1695620663844dccore0iuap-apcom-workbench1257a4c4YT; defaultOrg=1530661876902920193; tenantid=0000L6YTYEY5FUZPXE0000; languages=1_3-2_1-3_1-98_1; a00=bZee8efhdxqYH6wWk5arcaAYD7isDKyUnoPkiDfJSOMwMDAwTDZZVFlFWTVGVVpQWEUwMDAwYDI5MTAwMzMxNDY3NjE4MDhgMDAwMEw2WVRZRVk1RlVaUFhFMDAwMGA5OWVhNzY1NS0wMGEyLTRiZGEtYjIzYy0xOWFkZTM3ZWE1NzRgMWBgZTZiNThiZThhZjk1ZTdhZWExZTc5MDg2ZTU5MTk4MzEzMTMxYGBgMTUyNTY5NTQ2MDIxMDYzODg1OGBmYWxzZWBgMTY5NTYyMDY2Mzg0OWB5bXNzZXM6MGUxZGUxZTZlODlhNDQyMThjZTNhZDExOGZkY2ViZGZgZGl3b3JrYA; a10=MDEzNDM5MzI0MjU3OTY2NjM4NTA; Hm_lpvt_b97569d26a525941d8d163729d284198=1695620680; Hm_lpvt_e8002ef3d9e0d8274b5b74cc4a027d08=1695620680; yht_access_token=bttMEpNM2JUREU1TElRbW8wZlpnMXE2eWNIZ0FqU05xbE5DZmZsVTBZNGZsMVpJK1ZkRkZSZW9qRkxIY0pGN0xLU19fYmlwLWRhaWx5LnlvbnlvdWNsb3VkLmNvbQ..__8df4684f554fc93ddc9d4818c03f873e_1695621095236dccore0iuap-apcom-workbench89eb867dYT; multilingualFlag=true; timezone=UTC+08:00; language=001; locale=zh_CN; orgId=; defaultOrg=; tenantid=h6q8321v; theme=; languages=1_3-2_1-3_1; newArch=false; sysid=diwork; a00=7_ecvDzABfEbLnukPgxWrDlEUSNiGZexIg5pqop2XZ9oNnE4MzIxdmAxODU3ODgxMjgwMDU3NjAwYGg2cTgzMjF2YGVjMjQ2ZGFiLTFmZGMtNDhmZC05ZjAxLTFlMGViMGY4YTNjNGAxYGBlNjk4YjVlN2E3YjAyZDUyNTg1NGBgYDI3MjI4MTgxMDc4MTc0NzJgZmFsc2VgYDE2OTU2MjEwOTUyMzlgeW1zc2VzOmU0MjVlM2Q0ZTdkY2FhOWZiNTMyODIxZTlhZDQ3NTljYHU4YzMuMGA; n_f_f=false; wb_at=LMjoosqsvj6misqn8tuNHFOvQZBBjwjbnlahmd; jDiowrkTokenMock=bttMEpNM2JUREU1TElRbW8wZlpnMXE2eWNIZ0FqU05xbE5DZmZsVTBZNGZsMVpJK1ZkRkZSZW9qRkxIY0pGN0xLU19fYmlwLWRhaWx5LnlvbnlvdWNsb3VkLmNvbQ..__8df4684f554fc93ddc9d4818c03f873e_1695621095236dccore0iuap-apcom-workbench89eb867dYT; a10=ODE1MzQyODQ0MjU4MDU0OTQ3MzA; XSRF-TOKEN=FIX_H1B0AJ9JXFDSC2W7HJFK4ULPH!161527");
            conn.setReadTimeout(60*1000);
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = new OutputStreamWriter(
                    conn.getOutputStream());    		
            out.write(Params);
            out.flush();
            InputStream inputStream = conn.getInputStream();
            //读取响应
            BufferedInputStream bfInput = new BufferedInputStream(inputStream);
            fos = new FileOutputStream(filePath);
            int size = 0;
            while ((size = bfInput.read(buf)) != -1) {
            	fos.write(buf, 0, size);
            }
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                	fos.close();
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public static JSONObject getJSONOBject(JSONObject jsonObject) {

        try {

        	return sendPost("http://luoboshop.com/robo/vendingMachineController/getVendingMachineData", jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    
    @SuppressWarnings("resource")
	public static JSONArray readFile(String filePathString) {
    	JSONArray parseArray = new JSONArray();
    	try {
//    		String filePathString = "D:\\Program Files\\Desktop\\productSku.json";
    		InputStream fileInputStream = new FileInputStream(new File(filePathString));
    		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
    		
    		StringBuffer stringBuffer = new StringBuffer();
    		String lineStringBuffer="";
    		while((lineStringBuffer=bufferedReader.readLine())!=null) {
    			stringBuffer.append(lineStringBuffer);
    		}
    		
    		parseArray = JSONArray.parseArray(stringBuffer.toString());
		} catch (Exception e) {
			// TODO: handle exception
		}
    	return parseArray;
    }
 
}
